package com.eboss2.sbs.activity.base;

import android.annotation.SuppressLint;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.sdk.android.ams.common.util.Md5Util;
import com.cxmscb.cxm.processproject.FirstService;
import com.cxmscb.cxm.processproject.PlayerMusicService;
import com.cxmscb.cxm.processproject.SecondService;
import com.eboss2.sbs.R;
import com.eboss2.sbs.Tts.BdTts;
import com.eboss2.sbs.enums.TypeBottomTab;
import com.eboss2.sbs.myapplication.MyApplication;
import com.eboss2.sbs.receiver.ScreenReceiverUtil;
import com.eboss2.sbs.util.ScreenManager;
import com.hxchat.utils.APPConfig;
import com.hxchat.utils.SharedPreferencesUtils;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;
import com.mytools.tool.activityManager.MyActivityManager;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tool.utils.utils.StatusBarUtil;
import com.tool.utils.utils.UtilPreference;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

@SuppressWarnings("deprecation")
public class MainTabActivity extends TabActivity implements OnTabChangeListener
{

	private static final String TAG = "MainTabActivity";

    private Handler mHandler;
	
	private static final String BOTTOM_TAG = "bottom_menu_";
	
	TypeBottomTab[] tabs = TypeBottomTab.values();
	private TabHost mTabHost;
	private int mCurrentTabIndext = 0;

	// 动态注册锁屏等广播
	private ScreenReceiverUtil mScreenListener;
	// 1像素Activity管理类
	private ScreenManager mScreenManager;

	private ScreenReceiverUtil.SreenStateListener mScreenListenerer = new ScreenReceiverUtil.SreenStateListener() {
		@Override
		public void onSreenOn() {
			// 亮屏，移除"1像素"
			mScreenManager.finishActivity();
		}

		@Override
		public void onSreenOff() {
			// 接到锁屏广播，将SportsActivity切换到可见模式
			// "咕咚"、"乐动力"、"悦动圈"就是这么做滴
//            Intent intent = new Intent(SportsActivity.this,SportsActivity.class);
//            startActivity(intent);
			// 如果你觉得，直接跳出SportActivity很不爽
			// 那么，我们就制造个"1像素"惨案
			mScreenManager.startActivity();
		}

		@Override
		public void onUserPresent() {
			// 解锁，暂不用，保留
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);

		setContentView(R.layout.basic_tab);
		MyActivityManager.getInstance().addActivity(this);
		StatusBarUtil.setColor(this, getResources().getColor(R.color.statusBar), 0);


        mHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:
//                        Toast.makeText(MainTabActivity.this,"注册成功",Toast.LENGTH_SHORT).show();
                        //注册成功之后直接登录
                        ECMChatLogin();
                        break;
                    case 0:
//                        Toast.makeText(MainTabActivity.this,"注册失败"+msg.obj.toString(),Toast.LENGTH_LONG).show();
                        break;
                    case 2:
//                        Toast.makeText(MainTabActivity.this,"登录成功",Toast.LENGTH_LONG).show();
                        break;
                    case 3:
//                        Toast.makeText(MainTabActivity.this,"登录失败"+msg.obj.toString(),Toast.LENGTH_LONG).show();
                        //没有账号直接注册
                        register();
                        break;
                }
            }
        };


		
		initView();

		setMoreService();
		BdTts.getInstance(this);


		ECMChatLogin();
		setNotify();
	}


	private void setNotify(){
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
			// 通知渠道的id
			String id = "1";
			// 用户可以看到的通知渠道的名字.
			CharSequence name = "notification channel";
			// 用户可以看到的通知渠道的描述
			String description = "notification description";
//			int importance = NotificationManager.IMPORTANCE_HIGH;
			NotificationChannel mChannel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
			// 配置通知渠道的属性
			mChannel.setDescription(description);
			// 设置通知出现时的闪灯（如果 android 设备支持的话）
			mChannel.enableLights(false);
			mChannel.setLightColor(Color.RED);
			// 设置通知出现时的震动（如果 android 设备支持的话）
			mChannel.enableVibration(true);
			mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
			//最后在notificationmanager中创建该通知渠道
			mNotificationManager.createNotificationChannel(mChannel);
		}
	}


	/**
	 * 正则替换所有特殊字符
	 * @param orgStr
	 * @return
	 */
	public static String replaceSpecStr(String orgStr){
		if (null!=orgStr&&!"".equals(orgStr.trim())) {
			String regEx="[\\s~·`!！@#￥$%^……&*（()）\\-——\\-_=+【\\[\\]】｛{}｝\\|、\\\\；;：:‘'“”\"，,《<。.》>、/？?]";
			Pattern p = Pattern.compile(regEx);
			Matcher m = p.matcher(orgStr);

			return m.replaceAll("_");
		}
		return null;
	}


	private void ECMChatLogin() {
		Log.d(TAG, "EMClient.getInstance().login");
//		final String username = UtilPreference.getStringValue(this, "username");
		final String username = replaceSpecStr(UtilPreference.getStringValue(this, "username"));
		final String password = UtilPreference.getStringValue(this, "password");
		final String pwd = Md5Util.getInstance().md5_32(password);
		Log.e(TAG, pwd);
		Log.e(TAG, username);
		EMClient.getInstance().login(username, pwd, new EMCallBack() {

			@Override
			public void onSuccess() {
				Log.e(TAG, "login: onSuccess");

//				SharedPreferencesUtils.setParam(MainTabActivity.this, APPConfig.USER_NAME,username);
//				SharedPreferencesUtils.setParam(MainTabActivity.this, APPConfig.PASS_WORD,pwd);
				// ** manually load all local groups and conversation
				EMClient.getInstance().groupManager().loadAllGroups();
				EMClient.getInstance().chatManager().loadAllConversations();


			}

			@Override
			public void onProgress(int progress, String status) {
				Log.e(TAG, "login: onProgress");
			}

			@Override
			public void onError(final int code, final String message) {
//				runOnUiThread(new Runnable() {
//					public void run() {
//						Log.e(TAG, "login: onError: " + code+":"+message);
//					}
//				});
                Log.e(TAG, "login: onError: " + code+":"+message);
                if (code == 204){
                    Message msg=new Message();
                    msg.what=3;
                    msg.obj=message;
                    mHandler.sendMessage(msg);
                }
			}
		});
	}


    /**
     * 注册方法
     */
    private void register(){

		final String username = replaceSpecStr(UtilPreference.getStringValue(this, "username"));
        final String password = UtilPreference.getStringValue(this, "password");
        final String pwd = Md5Util.getInstance().md5_32(password);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().createAccount(username.toLowerCase(),pwd);
                    Log.e(TAG,"注册成功");
                    Message msg=new Message();
                    msg.what=1;
                    mHandler.sendMessage(msg);

                } catch (HyphenateException e) {
                    Message msg=new Message();
                    msg.what=0;
                    msg.obj=e.toString();
                    mHandler.sendMessage(msg);
                    Log.e(TAG,"注册失败");
                }
            }
        }).start();
    }



	private void setMoreService(){

		this.startService(new Intent(this,FirstService.class));
		this.startService(new Intent(this,SecondService.class));
		this.startService(new Intent(this,PlayerMusicService.class));

		// 1. 注册锁屏广播监听器
		mScreenListener = new ScreenReceiverUtil(this);
		mScreenManager = ScreenManager.getScreenManagerInstance(this);
		mScreenListener.setScreenReceiverListener(mScreenListenerer);


	}
	
	private void initView()
	{
		mTabHost = getTabHost();
		mTabHost.setOnTabChangedListener(this);
		if(mTabHost.getChildCount()!=0){mTabHost.clearAllTabs();}
		int tabnums = tabs.length;
		for (int i = 0; i < tabnums; i++) {
			RelativeLayout mLayoutTab = (RelativeLayout) getLayoutInflater().inflate(R.layout.basic_tab_view, null);
			ImageView tabIcon1 = (ImageView) mLayoutTab.findViewById(R.id.tab_img);
			tabIcon1.setBackgroundResource(tabs[i].getTabIcon());
			TextView tabTv1 = (TextView) mLayoutTab.findViewById(R.id.tab_txt);
			tabTv1.setText(tabs[i].getTabName());
			mTabHost.addTab(mTabHost.newTabSpec(BOTTOM_TAG+i).setIndicator(mLayoutTab).setContent(new Intent(MainTabActivity.this, tabs[i].getTargetClass())));
		}
		mTabHost.setCurrentTab(mCurrentTabIndext);
	}
	
	@Override
	public void onTabChanged(String arg0){}
	
	@Override
	protected void onNewIntent(Intent intent)
	{
		super.onNewIntent(intent);
	}
	
	@Override
	protected void onResume() {
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		ImageLoader.getInstance().clearMemoryCache();
		super.onDestroy();

		if (mScreenListener != null){
			mScreenListener.stopScreenReceiverListener();
			mScreenListener = null;
			mScreenListenerer = null;
		}
	}
	
}
